package com.sgl.retrofitdemo.ui.base;

import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.sgl.retrofitdemo.RetrofitApplication;
import com.sgl.retrofitdemo.net.BaseResponse;
import com.sgl.retrofitdemo.net.exception.ResponseException;
import com.sgl.retrofitdemo.utils.CustomToast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by sunqiyong on 2016/11/13.
 */

public class DefaultErrorSubscriber<T> extends DefaultSubscriber<T> {
    @Override
    public void onError(Throwable e) {
        Log.e("qwer","--->" + e.getMessage());
        if (e instanceof ResponseException) {
            ResponseException responseException = (ResponseException) e;
            switch (responseException.getCode()) {
                case 500: {
                    Log.e("qwer","--->500");
                    break;
                }

                case 505: {
                    Log.e("qwer","--->505");
                    // 重新登录
                    CustomToast.makeText(RetrofitApplication.getInstance(), "DefaultErrorSubscriber : 重新登录", Toast.LENGTH_LONG).show();
                    //MarsApplication.getInstance().startActivity(LoginAndRegisterActivity.getStartUpIntent(MarsApplication.getInstance(), false));
                    break;
                }

                default: {
                    break;
                }
            }
        } else if (e instanceof JSONException) {
            // FIXME: PHP 没有修改 data 的 [] {} 时，预处理解析出 message
            // syntax error, expect {, actual pos 46, json : {"code":505,"message":"用户会话已过期，请重新登录","data":[]}, fieldName data
            try {
                Matcher matcher = Pattern.compile("(?<=\\{)(\\S+)(?=\\})").matcher(e.getMessage());
                while (matcher.find()) {
                    String result = matcher.group();
                    BaseResponse res = JSON.parseObject("{" + result + "}", BaseResponse.class);
                    if (505 == res.getCode() || 504 == res.getCode()) {
                        //此处如果返回错误信息是505或者是504，那么就是会话过期，要重新登陆，
                        CustomToast.makeText(RetrofitApplication.getInstance(), "DefaultErrorSubscriber : " +  res.getMessage(), Toast.LENGTH_LONG).show();
                        //CustomToast.makeText(RetrofitApplication.getInstance(), res.getMessage(), Toast.LENGTH_LONG).show();
                        //MarsApplication.getInstance().startActivity(LoginAndRegisterActivity.getStartUpIntent(MarsApplication.getInstance(), false));
                        break;
                    }
                }
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        }

    }
}
